﻿# define IsNotEnableChechUserRight
# undef IsNotEnableChechUserRight
//创建时间: 2011-04-08
//创建作者: 李城
//功能说明: CMS系统 用户登录验证 
using System;
using System.Collections.Generic;
using System.Text;
using TRPOP.CMS.Model;
using System.Data;
using TRPOP.CMS.Business;
using TRPOP.CMS.Plugin;
using System.Web;
using TRPOP.Common;
namespace TRPOP.CMS.UserManage
{
    public class PermissionAdminManage : IAdminUser
    {

        #region 基本变量
        AdminUserManage mAdminUserManage = new AdminUserManage();
        /// <summary>
        /// Session 标识
        /// </summary>
        const string mstrAdministratorship = "Administratorship";
        /// <summary>
        /// 缓存Key 所有的权限码
        /// </summary>
        const string mstrAllPermissionCahceKey = "AllPermissionCahceKey";
        #endregion

        /// <summary>
        /// 用户登陆,并将信息保存到session或cookie里
        /// </summary>
        /// <param name="strUserName"></param>
        /// <param name="strPassword"></param>
        /// <param name="strErrorInfo"></param>
        /// <returns></returns>
        public bool AdminLogin(string strUserName, string strPassword)
        {
#if IsNotEnableChechUserRight
                return true;
#endif
            strUserName = strUserName.Trim().SQLFilter();
            strPassword = strPassword.Trim().MD5Normal();
            List<AdminUserInfo> olist = mAdminUserManage.GetListByCondition(1, " and  [LogName]='" + strUserName + "'", "");
            if (olist != null && olist.Count > 0 && olist[0].LogPWD == strPassword)
            {
                SaveCurrentInfo(olist[0]);//将用户信息保存至session
                AdminUserInfo oAdminUserInfo = olist[0];
                oAdminUserInfo.LastLogTime = DateTime.Now;
                mAdminUserManage.Save(oAdminUserInfo);
                SaveUserInfoToCookie(oAdminUserInfo);//将用户名和密码添加至客户端Cookie
                return true;
            }
            return false;
        }

        /// <summary>
        /// 检验用户是否登录
        /// </summary>
        /// <returns></returns>
        public bool CheckLogin()
        {
#if IsNotEnableChechUserRight
                return true;
#endif
            return (getUserBaseInfo() != null && getUserBaseInfo() is AdminUserInfo);
        }

        /// <summary>
        /// 获取用户登录的信息
        /// </summary>
        /// <returns></returns>
        public object getUserBaseInfo()
        {
#if IsNotEnableChechUserRight
                return getUserBaseInfo(1);
#endif
            return GetCurrentInfo();
        }


        /// <summary>
        /// 根据用户id获取用户名
        /// </summary>
        /// <param name="strUserName"></param>
        /// <returns></returns>
        public string GetAdminNameById(int intUserId)
        {
            AdminUserInfo oUserBaseInfo = getUserBaseInfo(intUserId) as AdminUserInfo;
            if (oUserBaseInfo != null)
                return oUserBaseInfo.Name;
            return "";
        }

        /// <summary>
        /// 获取用户登录的信息
        /// </summary>
        /// <returns></returns>
        public object getUserBaseInfo(int intUserId)
        {
            return mAdminUserManage.GetInfoById(intUserId);
        }


        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        public object GetCurrentInfo()
        {
            try
            {
                int testSessionCount = System.Web.HttpContext.Current.Session.Count;
            }
            catch
            {
                return GetUserInfoByCookie();
            }
            return (System.Web.HttpContext.Current.Session[mstrAdministratorship] != null) ? System.Web.HttpContext.Current.Session[mstrAdministratorship] : GetUserInfoByCookie();
        }
        /// <summary>
        /// 保存当前登陆用户信息
        /// </summary>
        /// <param name="obj"></param>
        public void SaveCurrentInfo(object obj)
        {
            System.Web.HttpContext.Current.Session[mstrAdministratorship] = obj;
            System.Web.HttpContext.Current.Session.Timeout = 20;
        }
        public void LoginOut()
        {
            HttpContext.Current.Session.Abandon();
            RemoveCookie();
            return;
        }

        /// <summary>
        /// 根据验证码枚举值判断用户权限
        /// </summary>
        /// <param name="oPermissionKeys"></param>
        /// <returns></returns>
        public bool CheckUserPermission(PermissionKeys.PermissionEnum oPermissionKeys)
        {
            AdminUserInfo oAdminUserInfo = GetCurrentInfo() as AdminUserInfo;
            if (oAdminUserInfo == null)
                oAdminUserInfo = new AdminUserInfo();
            if (
                oPermissionKeys == PermissionKeys.PermissionEnum.NullKey//如果当前页面没有配置权限，则返回true
                || oAdminUserInfo.PermissionIds.Trim().ToLower() == "all"//如果权限码为all 则返回true
                )
                return true;
            List<UserPermissionInfo> oList = GetAllPermissionInfo();
            if (oList == null || oList.Count <= 0)//如果权限码表未配置，则返回false
                return false;
            return CheckIsHavePermission(oPermissionKeys, oAdminUserInfo, oList);
        }


        /// <summary>
        /// 根据验证码枚举值判断用户权限
        /// </summary>
        /// <param name="oPermissionKeys"></param>
        /// <returns></returns>
        public bool CheckUserPermission(string oPermissionKey)
        {
            List<UserPermissionInfo> oList = GetAllPermissionInfo();
            AdminUserInfo oAdminUserInfo = GetCurrentInfo() as AdminUserInfo;
            UserPermissionInfo oUserPermissionInfo = oList.Find(delegate(UserPermissionInfo TempObj) { return TempObj.KeyWord == oPermissionKey; });
            if (oAdminUserInfo != null && oUserPermissionInfo != null && (oAdminUserInfo.PermissionIds.Trim().ToLower() == "all" || oAdminUserInfo.PermissionIds.Contains("|" + oUserPermissionInfo.UserRightCodeId + "|")))
                return true;
            return false;
        }


        /// <summary>
        /// 验证用户权限
        /// </summary>
        /// <param name="oPermissionKeys"></param>
        /// <param name="oAdminUserInfo"></param>
        /// <param name="oList"></param>
        /// <returns></returns>
        public bool CheckIsHavePermission(PermissionKeys.PermissionEnum oPermissionKeys, AdminUserInfo oAdminUserInfo, List<UserPermissionInfo> oList)
        {
            string strPermissionKeyName = PermissionKeys.GetPermissionKey(oPermissionKeys);
            UserPermissionInfo oUserPermissionInfo = oList.Find(delegate(UserPermissionInfo TempObj) { return TempObj.KeyWord == strPermissionKeyName; });
            switch (strPermissionKeyName.Trim().Substring(0, strPermissionKeyName.Trim().IndexOf("_")))
            {
                case "Node":
                    foreach (UserPermissionInfo oTempInfo in oList.FindAll(delegate(UserPermissionInfo TempObj) { return ((TempObj.KeyWord == "NodeContent_all") || (TempObj.KeyWord == "NodeContent_Node")); }))
                    {
                        if (oAdminUserInfo.PermissionIds.Contains("|" + oTempInfo.UserRightCodeId.ToString() + "|"))
                            return true;
                    }
                    return false;
                case "Content":
                    foreach (UserPermissionInfo oTempInfo in oList.FindAll(delegate(UserPermissionInfo TempObj) { return (TempObj.KeyWord == "NodeContent_all") || (TempObj.KeyWord == "NodeContent_Content"); }))
                    {
                        if (oAdminUserInfo.PermissionIds.Contains("|" + oTempInfo.UserRightCodeId.ToString() + "|"))
                            return true;
                    }
                    return false;
                case "SystemManage":
                    if (oUserPermissionInfo == null)
                    {
                        //如果页面权限码没有在数据库里配置，那么只要包含 SystemManage_All 或 SystemManage_Other 的权限 即可有权限访问页面
                        string strAllKey = PermissionKeys.GetPermissionKey(PermissionKeys.PermissionEnum.SystemManage_All);
                        string strOtherKey = PermissionKeys.GetPermissionKey(PermissionKeys.PermissionEnum.SystemManage_Other);
                        foreach (UserPermissionInfo oTempInfo in oList.FindAll(delegate(UserPermissionInfo TempObj) { return ((TempObj.KeyWord == strAllKey) || (TempObj.KeyWord == strOtherKey)); }))
                        {
                            if (oAdminUserInfo.PermissionIds.Contains("|" + oTempInfo.UserRightCodeId + "|"))
                                return true;
                        }
                        return false;
                    }
                    else
                    {
                        if (oAdminUserInfo.PermissionIds.Contains("|" + oUserPermissionInfo.UserRightCodeId + "|"))//如果用户包含当前页面的权限码
                            return true;
                        oUserPermissionInfo = oList.Find(delegate(UserPermissionInfo TempObj) { return TempObj.KeyWord == PermissionKeys.GetPermissionKey(PermissionKeys.PermissionEnum.SystemManage_All); });
                        if (oUserPermissionInfo != null && oAdminUserInfo.PermissionIds.Contains("|" + oUserPermissionInfo.UserRightCodeId + "|"))//如果用户有 SystemManage_All 的权限
                            return true;
                        return false;
                    }
                case "Plugin":
                    if (oUserPermissionInfo == null)
                    {
                        //如果页面权限码没有在数据库里配置，那么只要包含 Plugin_All 的权限 即可有权限访问页面
                        UserPermissionInfo oInfo = oList.Find(delegate(UserPermissionInfo TempObj) { return TempObj.KeyWord == PermissionKeys.GetPermissionKey(PermissionKeys.PermissionEnum.Plugin_All); });
                        if (oInfo != null && oAdminUserInfo.PermissionIds.Contains("|" + oInfo.UserRightCodeId + "|"))
                            return true;
                        return false;
                    }
                    else
                    {
                        if (oAdminUserInfo.PermissionIds.Contains("|" + oUserPermissionInfo.UserRightCodeId + "|"))//如果用户包含当前页面的权限码
                            return true;
                        oUserPermissionInfo = oList.Find(delegate(UserPermissionInfo TempObj) { return TempObj.KeyWord == PermissionKeys.GetPermissionKey(PermissionKeys.PermissionEnum.Plugin_All); });
                        if (oUserPermissionInfo != null && oAdminUserInfo.PermissionIds.Contains("|" + oUserPermissionInfo.UserRightCodeId + "|"))//如果用户有 Plugin_All 的权限
                            return true;
                        return false;
                    }
            }
            return false;
        }
        /// <summary>
        /// 获取所有的权限码集合
        /// </summary>
        /// <returns></returns>
        public List<UserPermissionInfo> GetAllPermissionInfo()
        {
            /*
             * 2011.07.07 lcheng 原来的实现代码
             * 
             * 
            TRPOP.CMS.Plugin.ICache ooCacheAccess = TRPOP.CMS.Plugin.ICacheAccess.GetInstance();
            object obj = ooCacheAccess.Read(mstrAllPermissionCahceKey);
            if (obj != null && obj is List<UserPermissionInfo>)
                return obj as List<UserPermissionInfo>;
            return new UserPermissionManage().GetListByCondition(0, "", "");
            */
            return CacheHelper.GetByICache<List<UserPermissionInfo>>(
                    mstrAllPermissionCahceKey,
                    60 * 10,
                    ICacheAccess.GetInstance(),
                    () =>
                    {
                        return new UserPermissionManage().GetListByCondition(0, "", "");
                    }
            );

        }
        /// <summary>
        /// 根据父id获取所有的权限码集合
        /// </summary>
        /// <param name="intParentid"></param>
        /// <returns></returns>
        public List<object> GetPermissionListByParentId(int intParentid)
        {
            List<object> oList = new List<object>();
            foreach (UserPermissionInfo oTempInfo in GetAllPermissionInfo().FindAll(delegate(UserPermissionInfo TempObj) { return TempObj.ParentId == intParentid; }))
            {
                oList.Add(oTempInfo);
            }
            return oList;
        }
        /// <summary>
        /// 获取当前用户可操作的所有节点。
        /// 格式如下：1,2,3,4,5,6 。 如果全部，则为all。
        /// </summary>
        /// <returns></returns>
        public string GetEnabledNodeIds()
        {
            AdminUserInfo oAdminUserInfo = getUserBaseInfo() as AdminUserInfo;
            if (oAdminUserInfo == null || oAdminUserInfo.NodeIds.IsEmpty())
                return "0";
            string strReturn = oAdminUserInfo.NodeIds.Replace("|", ",").Trim();
            if (strReturn.StartsWith(","))
                strReturn = strReturn.Substring(1);
            if (strReturn.EndsWith(","))
                strReturn = strReturn.Remove(strReturn.Length - 1);
            return strReturn.Trim().ToLower();
        }

        /// <summary>
        /// 保存当前用户信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool SaveUserInfo(object obj)
        {
            if (new AdminUserManage().Save(obj as AdminUserInfo) == EnumSubmitResult.Success)
            {
                object objUserInfo = getUserBaseInfo();
                if (objUserInfo != null && objUserInfo is AdminUserInfo && (objUserInfo as AdminUserInfo).UserBaseId == (obj as AdminUserInfo).UserBaseId)
                {
                    SaveCurrentInfo(obj as AdminUserInfo);
                    SaveUserInfoToCookie(obj as AdminUserInfo);
                }
                return true;
            }
            return false;
        }


        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="intUserID"></param>
        /// <returns></returns>
        public bool DeleteUserInfoById(int intUserID)
        {
            return new AdminUserManage().DeleteInfoById(intUserID) == EnumSubmitResult.Success;
        }
        /// <summary>
        /// 获取所有的用户信息
        /// </summary>
        /// <param name="topn"></param>
        /// <param name="condition"></param>
        /// <param name="orderby"></param>
        /// <returns></returns>
        public List<object> GetListByConditionForRealPubCount(int topn, string condition, string orderby)
        {
            return new AdminUserManage().GetListByConditionForRealPubCount(topn, condition, orderby);
        }
        /// <summary>
        /// 根据条件返回用户 List 
        /// </summary>
        /// <param name="topn"></param>
        /// <param name="condition"></param>
        /// <param name="orderby"></param>
        /// <returns></returns>
        public List<object> GetUserListByCondition(int topn, string condition, string orderby)
        {
            List<object> oList = new List<object>();
            foreach (AdminUserInfo oTempInfo in new AdminUserManage().GetListByCondition(topn, condition, orderby))
            {
                oList.Add(oTempInfo);
            }
            return oList;
        }


        /// <summary>
        /// 给当前用户增加节点权限
        /// </summary>
        /// <param name="intNodeId"></param>
        /// <returns></returns>
        public bool AddPermissionByNodeId(int intNodeId)
        {
            if (intNodeId <= 0)
                return false;
            AdminUserInfo oAdminUserInfo = GetCurrentInfo() as AdminUserInfo;
            if (oAdminUserInfo == null)
                return false;
            if (oAdminUserInfo.NodeIds.Trim().ToLower() == "all")
                return true;
            oAdminUserInfo.NodeIds += oAdminUserInfo.NodeIds.Trim().EndsWith("|") ? (intNodeId + "|") : ("|" + intNodeId + "|");
            return SaveUserInfo(oAdminUserInfo);
        }


        #region  后台用户Cookie的操作
        /// <summary>
        /// 将用户信息添加至客户端Cookie
        /// </summary>
        /// <param name="oAdminUserInfo"></param>
        public void SaveUserInfoToCookie(AdminUserInfo oAdminUserInfo)
        {
            CerateCookies(oAdminUserInfo.UserBaseId, oAdminUserInfo.LogPWD, DateTime.Now.AddHours(2));
        }

        /// <summary>
        /// 获取后台用户登陆信息
        /// </summary>
        /// <returns></returns>
        public object GetUserInfoByCookie()
        {
            HttpCookie oHttpCookie = GetAdminCookie();
            if (oHttpCookie == null)
                return null;
            int intUserID = 0;
            object objReturn = null;
            int.TryParse(GetAdminCookieUserID(oHttpCookie), out intUserID);
            objReturn = getUserBaseInfo(intUserID);
            if (objReturn != null && objReturn is AdminUserInfo && (objReturn as AdminUserInfo).LogPWD == GetAdminCookieUserPwd(oHttpCookie))
            {
                return objReturn;
            }
            return null;
        }
        #endregion

        #region 基本的Cookie操作
        /// <summary>
        /// Cookie命名
        /// </summary>
        private static string YorkCMSCookiesName
        {
            get
            {
                return "YorkCMS";
            }
        }
        /// <summary>
        /// Cookie加密的密钥
        /// </summary>
        private static string YorkCMSDesKey
        {
            get
            {
                return @"D3F51SD@!$2S";
            }
        }
        /// <summary>
        /// Cookie用户名标识
        /// </summary>
        private static string UserIDCookieFlag
        {
            get
            {
                return "YorkCMSUserID".MD5Normal();
            }
        }
        /// <summary>
        /// Cookie用户密码标识
        /// </summary>
        private static string UserPasswordCookieFlag
        {
            get
            {
                return "YorkCMSUserPassword".MD5Normal();
            }
        }
        /// <summary>
        /// 创建Cookies
        /// </summary>
        /// <param name="userInfo"></param>
        public static void CerateCookies(int userid, string paswd)
        {
            CerateCookies(userid, paswd, DateTime.Now.AddMinutes(20));
        }
        /// <summary>
        /// 创建Cookies并设置时间
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="paswd"></param>
        /// <param name="expires"></param>
        public static void CerateCookies(int userid, string paswd, DateTime expires)
        {
            HttpCookie cookie = new HttpCookie(YorkCMSCookiesName);
            cookie.Values[UserIDCookieFlag] = userid.ToString();
            cookie.Values[UserPasswordCookieFlag] = VS.Tools.Encryption.DES.Encode(paswd, YorkCMSDesKey).UrlEncode();
            if (HttpContext.Current.Request.Url.Host.Contains("."))
                cookie.Domain = HttpContext.Current.Request.Url.Host;
            cookie.Path = "/";
            //cookie.Expires = expires; 关闭浏览器，cookie即失效
            HttpContext.Current.Response.AppendCookie(cookie);
            cookie = GetAdminCookie();//test code
        }
        /// <summary>
        /// 读Cookie
        /// </summary>
        /// <returns></returns>
        public static HttpCookie GetAdminCookie()
        {
            HttpCookie ohcCookie = HttpContext.Current.Request.Cookies[YorkCMSCookiesName];
            return (ohcCookie == null || ohcCookie[UserIDCookieFlag] == null || ohcCookie[UserPasswordCookieFlag] == null) ? null : ohcCookie;
        }
        /// <summary>
        /// 读Cookie中的用户ID
        /// </summary>
        /// <param name="hcCookie"></param>
        /// <returns></returns>
        public static string GetAdminCookieUserID(HttpCookie hcCookie)
        {
            if (hcCookie == null)
                return "";
            return hcCookie.Values[UserIDCookieFlag].ToString();
        }
        /// <summary>
        /// 读Cookie中的用户密码
        /// </summary>
        /// <param name="hcCookie"></param>
        /// <returns></returns>
        public string GetAdminCookieUserPwd(HttpCookie hcCookie)
        {
            if (hcCookie == null)
                return "";
            return VS.Tools.Encryption.DES.Decode(HttpUtility.UrlDecode(hcCookie.Values[UserPasswordCookieFlag].ToString()), YorkCMSDesKey);
        }
        /// <summary>
        /// 删除Cookie
        /// </summary>
        public void RemoveCookie()
        {
            HttpCookie oHttpCookie = GetAdminCookie();
            if (oHttpCookie != null)
            {
                oHttpCookie.Expires = DateTime.Now.AddDays(-1);
                oHttpCookie.Values[UserIDCookieFlag] = "0";
                oHttpCookie.Values[UserPasswordCookieFlag] = "";
                if (HttpContext.Current.Request.Url.Host.Contains("."))
                    oHttpCookie.Domain = HttpContext.Current.Request.Url.Host;
                oHttpCookie.Path = "/";
                HttpContext.Current.Response.Cookies.Add(oHttpCookie);
            }
        }
        #endregion
    }
}
